﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Matrix.Common.Utility
{
    public class ByteHelper
    {
        // 把字节型转换成十六进制字符串

        public static string ByteToString(byte[] InBytes)
        {
            string StringOut = "";
            foreach (byte InByte in InBytes)
            {
                StringOut = StringOut + String.Format("{0:X2} ", InByte);
            }
            return StringOut;
        }
        // 把十六进制字符串转换成字节型

        public static byte[] StringToByte(string InString)
        {
            string[] ByteStrings;
            ByteStrings = InString.Trim().Split(" ".ToCharArray());
            byte[] ByteOut;
            ByteOut = new byte[ByteStrings.Length];
            for (int i = 0; i <= ByteStrings.Length - 1; i++)
            {
                ByteOut[i] = Convert.ToByte("0x" + ByteStrings[i], 16);
            }
            return ByteOut;
        }

        /// <summary>
        /// 截取字节数组
        /// </summary>
        /// <param name="srcBytes">要截取的字节数组</param>
        /// <param name="startIndex">开始截取位置的索引</param>
        /// <param name="length">要截取的字节长度</param>
        /// <returns>截取后的字节数组</returns>
        public static byte[] SubByte(byte[] srcBytes, int startIndex, int length)
        {
            var bufferStream = new System.IO.MemoryStream();
            byte[] returnByte = new byte[] { };
            if (srcBytes == null) { return returnByte; }
            if (startIndex < 0) { startIndex = 0; }
            if (startIndex < srcBytes.Length)
            {
                if (length < 1 || length > srcBytes.Length - startIndex) { length = srcBytes.Length - startIndex; }
                bufferStream.Write(srcBytes, startIndex, length);
                returnByte = bufferStream.ToArray();
                bufferStream.SetLength(0);
                bufferStream.Position = 0;
            }
            bufferStream.Close();
            bufferStream.Dispose();
            return returnByte;
        }

        /// <summary>
        /// 将两个BTYE组合转换返回USHORT类型（大端模式Big-endian）
        /// </summary>
        /// <param name="headByte"></param>
        /// <param name="tailByte"></param>
        /// <returns></returns>
        public static ushort ConvertBytesToUShort(byte headByte, byte tailByte)
        {
            var strPart1 = Convert.ToString(headByte, 2).PadLeft(8, '0');
            var strPart2 = Convert.ToString(tailByte, 2).PadLeft(8, '0');
            var usRet = Convert.ToUInt16(strPart1 + strPart2, 2);
            return usRet;
        }

        /// <summary>
        /// 将四个BTYE组合转换返回ULONG类型（大端模式Big-endian）
        /// </summary>
        /// <param name="headByte"></param>
        /// <param name="thirdByte"></param>
        /// <param name="tailByte"></param>
        /// <param name="secondByte"></param>
        /// <returns></returns>
        public static uint ConvertFourBytesToUInt(byte headByte, byte secondByte, byte thirdByte, byte tailByte)
        {
            var strPart1 = Convert.ToString(headByte, 2).PadLeft(8, '0');
            var strPart2 = Convert.ToString(secondByte, 2).PadLeft(8, '0');
            var strPart3 = Convert.ToString(thirdByte, 2).PadLeft(8, '0');
            var strPart4 = Convert.ToString(tailByte, 2).PadLeft(8, '0');
            var ulRet = Convert.ToUInt32(strPart1 + strPart2 + strPart3 + strPart4, 2);
            return ulRet;
        }

        /// <summary>
        /// 将四个BTYE组合转换返回ULONG类型（大端模式Big-endian）
        /// </summary>
        /// <returns></returns>
        public static byte[] ConvertUIntoToBytes(uint sourceValue)
        {
            var strHedixString = sourceValue.ToString("X2").PadLeft(8, '0');
            var strByteSource = strHedixString.Substring(0, 2) + " " + strHedixString.Substring(2, 2) + " " +
                                strHedixString.Substring(4, 2) + " " + strHedixString.Substring(6, 2);
            return StringToByte(strByteSource);
        }

        /// <summary>
        /// 将USHORT类型转换为两个BTYE组合返回（大端模式Big-endian）
        /// </summary>
        /// <param name="sourceValue"></param>
        /// <returns></returns>
        public static byte[] ConvertUShortToBytes(ushort sourceValue)
        {
            var strHedixString = sourceValue.ToString("X2").PadLeft(4, '0');
            var strByteSource = strHedixString.Substring(0, 2) + " " + strHedixString.Substring(2, 2);

            return StringToByte(strByteSource);
        }

        /// <summary> 
        /// 字符串转16进制字节数组 
        /// </summary> 
        /// <param name="hexString"></param> 
        /// <returns></returns> 
        private static byte[] StrToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        /// <summary> 
        /// 字节数组转16进制字符串 
        /// </summary> 
        /// <param name="bytes"></param> 
        /// <returns></returns> 
        public static string ByteToHexStr(byte[] bytes)
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }

        /// <summary> 
        /// 从汉字转换到16进制 
        /// </summary> 
        /// <param name="s"></param> 
        /// <param name="charset">编码,如"utf-8","gb2312"</param> 
        /// <param name="fenge">是否每字符用逗号分隔</param> 
        /// <returns></returns> 
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s += " ";//空格 
                //throw new ArgumentException("s is not valid chinese string!"); 
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        ///<summary> 
        /// 从16进制转换成汉字 
        /// </summary> 
        /// <param name="hex"></param> 
        /// <param name="charset">编码,如"utf-8","gb2312"</param> 
        /// <returns></returns> 
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格 
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }

    }
}
